<?php
namespace Home\Controller;

use Think\Controller;


class SmsController extends Controller
{
    /**
     * 设置session过期时间
     * @param int $expire 过期时间（单位：秒）
     */
    public function start_session($expire = 0)
    {
        if ($expire == 0) {
            $expire = ini_get('session.gc_maxlifetime');
        } else {
            ini_set('session.gc_maxlifetime', $expire);
        }

        if (empty($_COOKIE['PHPSESSID'])) {
            session_set_cookie_params($expire);
            session_start();
        } else {
            session_start();
            setcookie('PHPSESSID', session_id(), time() + $expire);
        }
    }

    /**
     * 生成6位随机数
     * @return string   返回存有6位随机数的SESSION
     */
    public function random()
    {
        $chars = '0123456789';
        mt_srand((double)microtime() * 1000000 * getmypid());
        $CheckCode = "";
        while (strlen($CheckCode) < 6) {
            $CheckCode .= substr($chars, (mt_rand() % strlen($chars)), 1);
        }
        $this->start_session(300); //让session在5分钟内有效
        $_SESSION['verify'] = $CheckCode; //生成的随机数存入SESSION
        return $_SESSION['verify'];
    }

    /**
     * 生成手机验证码
     */
    public function code()
    {
        header("Content-type:text/html;charset=utf-8");
        $email = $_POST['username']; //获取用户输入的邮箱
        $member = M('Member'); //实例化会员表，数据表首字母须大写，否则无法完成自动验证
        $condition['email'] = $email;
        $result = $member->where($condition)->select();
        if (!$result) { //未被注册
            $sendTo = $email; //用户提交的邮箱地址
            $subject = "用户注册提醒";
            $code = $this->random();
            $usernameArr=explode("@",$email);
            $username=$usernameArr[0];
            $content='<html><head>
                    <meta http-equiv="Content-Language" content="zh-cn"/>
                    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
                    </head>
                    <body>
                    <div style="width:60%;padding:30px 20px;background:#F9F9F9;">
                    <span style="font-weight:bold;font-size:16px;">Hi,' . $username . '</span><br/>
                    欢迎您注册<b>妈妈好菜网</b><br/>
                    您申请的验证码为：<font style="color:blue;">'.$code.'</font><br/>
                    请于5分钟内输入验证码完成验证，谢谢！:<br/>
                    <br/>
                    <font style="color:#999;">如果您已经拥有有妈妈好菜网的账号，请点击以下链接直接登录</font><br/>
                    http://localhost/login.html
                    </div>
                    </body>
                    </html>';

            $res=$this->sendmail($sendTo,$content,$username,$subject);
            if ($res) {//邮件发送成功
                echo "0";
            }else {//邮件发送失败，销毁SESSION
                unset($_SESSION['verify']);
                echo "1";
            }
        }else { //已被注册
            echo "2";
        }
    }

    /**
     * 手机号验证
     */
    public function phoneCheck(){
        header("Content-type:text/html;charset=utf-8");
        $phone=$_POST['phone'];//获取用户输入的电话号码
        $member = M('Member'); //实例化会员表，数据表首字母须大写，否则无法完成自动验证
        $condition['phone'] = $phone;
        $result = $member->where($condition)->select();
        if($result){
            echo "1";
            //echo '该手机号已被注册';
        }else{
            echo "0";
            //echo '手机号可用';
        }
    }

    /**
     * 用户名检测
     */
    public function nameCheck(){
        header("Content-type:text/html;charset=utf-8");
        $username=$_POST['username'];
        $user=M('Userinfo');
        $condition['username']=$username;
        $result=$user->where($condition)->select();
        if($result){
            echo "1";
        }else{
            echo "0";
        }
   }


    /**
     * 发送邮件函数
     * @param $sendTo 收件人邮箱地址
     * @param $content  邮件内容
     * @param $username    收件人姓名
     * @param $subject  邮件主题
     * @return bool     返回邮件是否发送成功
     */
    public function sendmail($sendTo,$content, $username, $subject)
    {
        $mail = new \Think\PHPMailer();
        $mail->IsSMTP(); // send via SMTP

        $mail->Host = C('MAIL_HOST'); // SMTP servers
        $mail->SMTPAuth = true; // turn on SMTP authentication
        $mail->Username = C('MAIL_USERNAME'); // SMTP username  注意：普通邮件认证不需要加 @域名
        $mail->Password = C('MAIL_PASSWORD'); // SMTP password
        $mail->From = C('MAIL_FROM'); // 发件人邮箱
        $mail->FromName = C('MAIL_FROMNAME'); // 发件人

        $mail->CharSet = C('MAIL_CHARSET'); // 这里指定字符集！
        $mail->Encoding = "base64";
        $mail->AddAddress($sendTo, $username); // 收件人邮箱和姓名
        $mail->SetFrom(C('MAIL_FROM'), '成都蓉枳企业管理有限公司');

        $mail->AddReplyTo(C('MAIL_FROM'), '成都蓉枳企业管理有限公司');
        //$mail->WordWrap = 50; // set word wrap 换行字数
        //$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment 附件
        //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");
        $mail->IsHTML(true); // send as HTML
        // 邮件主题
        $mail->Subject = $subject;
        // 邮件内容
        $mail->Body = $content;
        $mail->AltBody = "text/html";
    return $mail->Send();

    }

}



